package com.ruoyi.web.controller.basedata;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.ruoyi.basedata.domain.ElectricityAreaZoneJoin;
import com.ruoyi.basedata.domain.MeterSheets;
import com.ruoyi.basedata.service.IElectricityAreaZoneJoinService;
import com.ruoyi.basedata.service.IMeterSheetsService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.geometry.partitioning.BSPTree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 区域管理Controller
 *
 * @author gdqt
 * @date 2024-03-01
 */
@RestController
@RequestMapping("/basedata/meterSheets")
public class MeterSheetsController extends BaseController {
    @Autowired
    private IMeterSheetsService meterSheetsService;

    @Autowired
    private IElectricityAreaZoneJoinService electricityAreaZoneJoinService;

    /**
     * 查询区域管理列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:list')")
    @GetMapping("/list")
    public TableDataInfo list(MeterSheets meterSheets) {
        startPage();
        List<MeterSheets> list = meterSheetsService.selectMeterSheetsList(meterSheets);
        return getDataTable(list);
    }

    /**
     * 查询区域管理列表(树结构)
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:list')")
    @GetMapping("/listTree")
    public List<Tree<Object>> listTree(MeterSheets meterSheets) {
        List<MeterSheets> list = meterSheetsService.selectMeterSheetsList(meterSheets);
        long rootCount = list.stream().filter(item -> item.getParentId() == 0).count();
        if (rootCount > 0) {
            return transformToRootTreeList(list);
        } else {
            return transformToNoRootTreeList(list);
        }
    }

    /**
     * 导出区域管理列表
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:export')")
    @Log(title = "区域管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MeterSheets meterSheets) {
        List<MeterSheets> list = meterSheetsService.selectMeterSheetsList(meterSheets);
        ExcelUtil<MeterSheets> util = new ExcelUtil<MeterSheets>(MeterSheets.class);
        util.exportExcel(response, list, "区域管理数据");
    }

    /**
     * 获取区域管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(meterSheetsService.selectMeterSheetsById(id));
    }

    /**
     * 新增区域管理
     */
//    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:add')")
//    @Log(title = "区域管理", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody MeterSheets meterSheets) {
//        MeterSheets meterSheetsModel = new MeterSheets();
//        meterSheetsModel.setSheetsCode(meterSheets.getSheetsCode());
//        List<MeterSheets> sheetsList = meterSheetsService.selectMeterSheetsList(meterSheetsModel);
//        if (CollUtil.isNotEmpty(sheetsList)) {
//            return AjaxResult.error("已存在相同编号的区域记录，请换一个区域编号重试");
//        }
//        return toAjax(meterSheetsService.insertMeterSheets(meterSheets));
//    }

    /**
     * 新增区域管理
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:add')")
    @Log(title = "区域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MeterSheets meterSheets) {
        meterSheetsService.addMeterSheets(meterSheets);
        return success("区域新增成功");
    }




    /**
     * 修改区域管理
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:edit')")
    @Log(title = "区域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MeterSheets meterSheets) {
        MeterSheets record = meterSheetsService.selectMeterSheetsById(meterSheets.getId());
        if (!record.getSheetsCode().equals(meterSheets.getSheetsCode())) {
            MeterSheets meterSheetsModel = new MeterSheets();
            meterSheetsModel.setSheetsCode(meterSheets.getSheetsCode());
            List<MeterSheets> sheetsList = meterSheetsService.selectMeterSheetsList(meterSheetsModel);
            if (CollUtil.isNotEmpty(sheetsList)) {
                return AjaxResult.error("已存在相同编号的区域记录，请换一个区域编号重试");
            }
        }
        return toAjax(meterSheetsService.updateMeterSheets(meterSheets));
    }

    /**
     * 删除区域管理
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:remove')")
    @Log(title = "区域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        // 软删除，删除标志2
        for (Long id : ids) {
            MeterSheets record = meterSheetsService.selectMeterSheetsById(id);
            if (record != null) {
                record.setDelFlag(2L);
                meterSheetsService.updateMeterSheets(record);
            }
        }
        return success("删除成功");
//        return toAjax(meterSheetsService.deleteMeterSheetsByIds(ids));
    }

    /**
     * 区域树
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:list')")
    @GetMapping("/getAreaTree")
    public AjaxResult getAreaTree(@RequestParam("treeType") String treeType,
                                  @RequestParam(value = "sheetsCode",required = false)String sheetsCode,
                                  @RequestParam(value = "sheetsName",required = false)String sheetsName,
                                  @RequestParam(value = "sheetsAddr",required = false) String sheetsAddr,
                                  @RequestParam(value = "details",required = false) String details ,
                                  @RequestParam(value = "showDeviceCount", defaultValue="true") boolean showDeviceCount) {
        String[] split = treeType.split(",");
        //treeType = "0,2"时查询大表区域树和通用区域
        if ("2".equals(split[1])){
            return success(meterSheetsService.getAreaTree(2,sheetsName,sheetsCode,sheetsAddr,details,showDeviceCount));
        }
        //通用区域和小表区域
       /* else if ("1".equals(split[1])){
            return success(meterSheetsService.getAreaTree(1,sheetsName,sheetsCode,sheetsAddr,details,showDeviceCount));
        }else if ("4".equals(split[1])){
            return success(meterSheetsService.getAreaTree(4,sheetsName,sheetsCode,sheetsAddr,details,showDeviceCount));
        }else {
            return success(meterSheetsService.getAreaTree(3,sheetsName,sheetsCode,sheetsAddr,details,showDeviceCount));
        }*/
        return success(meterSheetsService.getAreaTree(Integer.parseInt(split[1]),sheetsName,sheetsCode,sheetsAddr,details,showDeviceCount));

    }


    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:list')")
    @GetMapping("/getAreaTreeLoss")
    public AjaxResult getAreaTreeLoss(@RequestParam("treeType") String treeType,
                                  @RequestParam(value = "sheetsCode",required = false)String sheetsCode,
                                  @RequestParam(value = "sheetsName",required = false)String sheetsName,
                                  @RequestParam(value = "sheetsAddr",required = false) String sheetsAddr,
                                  @RequestParam(value = "details",required = false) String details ,
                                  @RequestParam(value = "showDeviceCount", defaultValue="true") boolean showDeviceCount) {
        String[] split = treeType.split(",");
        return success(meterSheetsService.getAreaTreeLoss(Integer.parseInt(split[1]),sheetsName,sheetsCode,sheetsAddr,details,showDeviceCount));

    }




    /**
     * 区域树
     */
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:list')")
    @GetMapping("/getAreaTreeChildren")
    public AjaxResult getAreaTree(@RequestParam("pid")@NotNull Long pid) {
        return success(meterSheetsService.getAreaTreeChildren(pid));

    }





    //获取用户已分配的权限
    @PreAuthorize("@ss.hasPermi('basedata:meterSheets:list')")
    @GetMapping("/getAreaPermissionsByUserId")
    public AjaxResult getAreaPermissionsByUserId(@RequestParam("userId") Long userId){
        List<MeterSheets> list = meterSheetsService.getAreaPermissionsByUserId(userId);
        return success(list);
    }

    /**
    * @Description: 获取区域绑定的设备信息
    * @date: 2025/3/6 15:25
    * @author: zt
    */
    @GetMapping("/getBindTerminalList")
    public AjaxResult getBindTerminalList(@RequestParam("areaId") String areaId,@RequestParam("hookType") Long hookType){
        List<ElectricityAreaZoneJoin> list = meterSheetsService.getBindTerminalList(areaId,hookType);
        return success(list);
    }

    /**
    * @Description: 删除区域绑定的设备
    * @date: 2025/3/6 16:29
    * @author: zt
    */
    @DeleteMapping("/removeBindTerminal/{id}")
    public AjaxResult removeBindTerminal(@PathVariable Long id) {
        if(id == null || id==0){
            return success("删除失败");
        }
        electricityAreaZoneJoinService.deleteElectricityAreaZoneJoinById(id);
        return success("删除成功");
    }

    /**
     * 批量新增区域绑定设备
     */
    @Log(title = "区域管理", businessType = BusinessType.INSERT)
    @PostMapping("/addBindTemrinal")
    public AjaxResult addBindTemrinal(@RequestBody List<ElectricityAreaZoneJoin> list) {
        String tenantId = getLoginUser().getTenantId();
        if(!list.isEmpty()){
            list.forEach(electricityAreaZoneJoin -> {
                electricityAreaZoneJoin.setTenantId(tenantId);
            });
            electricityAreaZoneJoinService.saveBatch(list);
        }
        return success("新增成功");
    }

    /**
     * 修改区域绑定设备
     */
    @Log(title = "区域管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editBindTemrinal")
    public AjaxResult editBindTemrinal(@RequestBody ElectricityAreaZoneJoin entity) {
        Long id = entity.getId();
        ElectricityAreaZoneJoin oldEntity = electricityAreaZoneJoinService.getById(id);
        if(!StringUtils.isEmpty(entity.getUsed())){
            oldEntity.setUsed(entity.getUsed());
        }
        if(entity.getTerminalMark()!=null){
            oldEntity.setTerminalMark(entity.getTerminalMark());
            if(entity.getTerminalMark() == 0){
                oldEntity.setDownTime(new Date());
            }
        }
        electricityAreaZoneJoinService.getBaseMapper().updateById(oldEntity);
        return success("更新成功");
    }


    private List<Tree<Object>> transformToRootTreeList(List<MeterSheets> nodeList) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setChildrenKey("children");

        List<Tree<Object>> treeNodes = TreeUtil.build(nodeList, 0L, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId().toString());
                    tree.setParentId(treeNode.getParentId().toString());
                    tree.setName(treeNode.getSheetsName());
                    tree.putExtra("id", treeNode.getId());
                    tree.putExtra("tenantId", treeNode.getTenantId());
                    tree.putExtra("parentId", treeNode.getParentId());
                    tree.putExtra("code", treeNode.getSheetsCode());
                    tree.putExtra("name", treeNode.getSheetsName());
                    tree.putExtra("address", treeNode.getSheetsAddr());
                    tree.putExtra("details", treeNode.getDetails());
                    tree.putExtra("lng", treeNode.getLng());
                    tree.putExtra("lat", treeNode.getLat());
                    tree.putExtra("remark", treeNode.getRemark());
                });

        return treeNodes;
    }

    private List<Tree<Object>> transformToNoRootTreeList(List<MeterSheets> nodeList) {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setParentIdKey("parentId");
        treeNodeConfig.setChildrenKey("children");
        treeNodeConfig.setNameKey("sheetsName");
        List<Tree<Object>> treeNodes = new ArrayList<>();
        nodeList.forEach(meterSheets -> {
            Tree<Object> tree = new Tree<>(treeNodeConfig);
            tree.setId(meterSheets.getId());
            tree.setParentId(meterSheets.getParentId());
            tree.setName(meterSheets.getSheetsName());
            tree.putExtra("code", meterSheets.getSheetsCode());
            tree.putExtra("name", meterSheets.getSheetsName());
            tree.putExtra("address", meterSheets.getSheetsAddr());
            tree.putExtra("details", meterSheets.getDetails());
            treeNodes.add(tree);
        });

        return treeNodes;
    }

}
